package com.github.gexiao.middleware.hystrix.service.impl;

import com.github.gexiao.middleware.hystrix.service.FallbackHandler;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.reflect.MethodSignature;

import java.lang.reflect.Method;

public class DefaultFallbackHandler implements FallbackHandler<Object> {
    @Override
    public Object handler(ProceedingJoinPoint jp) {
        try {
            return getMethod(jp).getReturnType().newInstance();
        } catch (InstantiationException | IllegalAccessException | NoSuchMethodException e) {
            e.printStackTrace();
        }
        return null;
    }

    private Method getMethod(JoinPoint jp) throws NoSuchMethodException {
        Signature sig = jp.getSignature();
        MethodSignature methodSignature = (MethodSignature) sig;
        return jp.getTarget().getClass().getMethod(methodSignature.getName(), methodSignature.getParameterTypes());
    }
}
